const { verify } = require('../config.js/jwt');
const { User } = require('../models/users');

let publicApi = ['/api/users/login', '/register'];
module.exports = function () {
  return async (req, res, next) => {
    if (publicApi.includes(req.path)) return next();
    console.log('eq.method',req.method);
    
    if(req.method==='GET')  return next();
    try {
			const token = req.headers.authorization;
			let result = await verify(token, 'secret');
			req.user = await User.findById(result.id);
			console.log(req.user, 'token验证');
			global.log = {
				user: req.user.name,
				userId: req.user._id,
				method: req.method,
        url: req.url,
				desc: null
			};
			 next();
		} catch (err) {
			return res.status('401').json(err);
		}
	};
};
